{% extends "layout.html" %}

{% block body %}
<div class="discover">
  <h2>{{title}}</h2>
    <div>
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <h3 style="color: whitesmoke; margin-top: 0px !important; margin-bottom: 2.4rem;">CWA Library Convertor - Current Target Format - {{target_format}}</h3>
        <div>
          <a class="btn btn-default" href="{{ url_for('convert_library.show_convert_library_logs') }}" style="background-color: #334148; vertical-align: top; float: right; margin-left: 10px;">{{_('Run Archive')}}</a>
          <a class="btn btn-default" href="{{ url_for('convert_library.download_current_log', log_filename='convert-library.log') }}" style="background-color: #334148; vertical-align: top; float: right;">{{_('Download Log')}}</a>
        </div>
      </div>
      <div style="display: flex;
                  justify-content: space-between;
                  gap: 20px;">
        <p style="font-size: xx-small;max-width: 70%;">
          Upon loading this page, if you have previously started a run of the CWA Convert Library service either here in the Web UI or through the CLI, you will see the output of the most recent previous run below. 
          Once you start a run, you are free to leave the page and return whenever you want to check on the run's progress. If you wish to cancel a run that is still in progress, simply press the Cancel button above 
          and the run will terminate ASAP. If you wish to change the service's target format, please change your target format in the CWA Settings panel as desired.
        </p>
        <div>
          <a class="btn btn-default" href="{{ url_for('convert_library.cancel_convert_library') }}" style="vertical-align: top; float: right; width: 100px; margin-left: 10px;">{{_('Cancel')}}</a>
          <a class="btn btn-default" href="{{ url_for('convert_library.start_conversion') }}" style="vertical-align: top; float: right; width: 100px;">{{_('Start')}}</a>
          {% if current_user.role_admin() %}
          <div class="btn-group" role="group" aria-label="schedule" style="float: right; margin-right: 10px;">
            <button class="btn btn-default" onclick="scheduleConvertLibrary(5)">{{ _('Schedule 5m') }}</button>
            <button class="btn btn-default" onclick="scheduleConvertLibrary(15)">{{ _('Schedule 15m') }}</button>
          </div>
          {% endif %}
        </div>
      </div>
      <div class="progress-container" style="margin: 20px 0;">
        <div id="progress-bar" style="width: 0%; height: 25px; background-color: green; text-align: center; color: white;"></div>
      </div>
      <div class="row">
        <div class="logging_window" style="padding-left: 15px;
                                          padding-right: 15px;
                                          background: #0000003d;
                                          padding-top: 11px;
                                          padding-bottom: 1px;
                                          max-height: calc(100vh - 40rem);
                                          overflow-y: scroll;">
          <p id="innerStatus" style="color: whitesmoke; font-size: small;">No current or previous run to display. Press the Start button above to initiate a run.</p>
        </div>
      </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
  var timeout;
  
  // Notification helper - creates a dismissible Bootstrap alert
  function showNotification(message, type) {
    type = type || 'info'; // info, success, warning, danger
    const alertDiv = $('<div>')
      .addClass(`alert alert-${type} alert-dismissible fade in`)
      .attr('role', 'alert')
      .css({
        'position': 'fixed',
        'top': '70px',
        'right': '20px',
        'z-index': '9999',
        'min-width': '300px',
        'max-width': '500px',
        'box-shadow': '0 4px 8px rgba(0,0,0,0.2)'
      })
      .html(`
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        ${message}
      `);
    
    $('body').append(alertDiv);
    
    // Auto-dismiss after 4 seconds
    setTimeout(function() {
      alertDiv.alert('close');
    }, 4000);
  }

  function scheduleConvertLibrary(delayMinutes) {
    fetch('/cwa-internal/schedule-convert-library', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ delay_minutes: delayMinutes, username: '{{ current_user.name }}' })
    })
    .then(r => {
      if (!r.ok) {
        return r.json().then(err => {
          throw new Error(err.error || 'Failed to schedule');
        });
      }
      return r.json();
    })
    .then(data => {
      showNotification('{{ _("Convert Library scheduled successfully") }}', 'success');
    })
    .catch(err => {
      showNotification('{{ _("Error scheduling Convert Library") }}: ' + err.message, 'danger');
    });
  }
  
  async function getStatus() {
  
    let get;
    
    try {
      const res = await fetch("{{ url_for('convert_library.get_status')}}");
      get = await res.json();
    } catch (e) {
      console.error("Error: ", e);
    }
    
    // Check if get.status is a non-empty string
    if (get.status && get.status.trim() !== "") {
        document.getElementById("innerStatus").innerHTML = get.status.replace(/\n/g, "<br>");
    }

    if (get.progress) {
      const { current, total } = get.progress;
      if (total > 0) {
        const percentage = Math.round((current / total) * 100);
        const progressBar = document.getElementById("progress-bar");
        progressBar.style.width = percentage + "%";
        progressBar.textContent = percentage + "%";
      }
    }
    
    if (get.status.includes("CONVERT LIBRARY PROCESS TERMINATED BY USER")){
      // Add finished log
      document.getElementById("innerStatus").innerHTML;
      // Check if run was cancelled, make progress bar red if so
      const progressBar = document.getElementById("progress-bar");
      progressBar.style.backgroundColor = "#D22B2B"; // Cadmium Red
      // End script
      clearTimeout(timeout);
      return false;
    }

    if (get.status.includes("CWA Convert Library Service - Run Ended:")){
      // Add finished log
      document.getElementById("innerStatus").innerHTML;
      // Set the progress bar to 100%
      const percentage = 100;
      const progressBar = document.getElementById("progress-bar");
      progressBar.style.width = percentage + "%";
      progressBar.textContent = percentage + "%";
      // End script
      clearTimeout(timeout);
      return false;
    }
  
    timeout = setTimeout(getStatus, 1000);
  }
  
  getStatus();
  </script>
{% endblock %}